package com.yeyks.task;

import cn.hutool.core.date.DateUtil;
import com.yeyks.common.constants.activity.RedisKeyPreConstant;
import com.yeyks.consumer.dal.domain.UserDataStat;
import com.yeyks.consumer.service.UserDataStatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;

/**
 * @author shuai
 * @date 2019/11/07 19:15
 */
@Component
@Slf4j
public class PvUvTask {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserDataStatService userDataStatService;
    private static final String hyperLogLogKeyPre = RedisKeyPreConstant.STATISTICAL_MANAGEMENT_UNIQUE_VISITOR_PRE + "userId";
    private static final String pv = RedisKeyPreConstant.STATISTICAL_MANAGEMENT_UNIQUE_PV;

    /**
     * 每天凌晨执行一次
     */
    @Scheduled(cron = "${schedule.stat.pu}")
    private void activityDoubleDanTask() {
        log.info("PV和UV定时任务开始-----------，time = {}", DateUtil.formatDateTime(new Date()));
        Date date = DateUtil.offsetDay(new Date(), -1).toJdkDate();
        Long size = redisTemplate.opsForHyperLogLog().size(hyperLogLogKeyPre);
        UserDataStat userDataStat = new UserDataStat();
        userDataStat.setUv(null == size ? 0 : size.intValue());
        userDataStat.setActivityId(8888);
        //PV
        Integer count = (Integer) redisTemplate.opsForValue().get(pv);
        userDataStat.setPv(null == count ? 0 : count);
        userDataStat.setDate(date);
        userDataStat.setCreateTime(date);
        boolean save = userDataStatService.save(userDataStat);
        if (save) {
            redisTemplate.delete(pv);
            redisTemplate.delete(hyperLogLogKeyPre);
        }
        log.info("PV和UV定时任务结束");
    }
}
